package com.ruoyi.system.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Struct;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysProject;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysContract;
import com.ruoyi.system.domain.SysTender;
import com.ruoyi.system.domain.vo.CodeVo;
import com.ruoyi.system.mapper.SysContractMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysProjectMapper;
import com.ruoyi.system.service.ISysProjectService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 项目Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-27
 */
@Service
public class SysProjectServiceImpl implements ISysProjectService {
    @Autowired
    private SysProjectMapper sysProjectMapper;

    @Autowired
    private SysContractMapper sysContractMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    /**
     * 查询项目
     *
     * @param projectId 项目主键
     * @return 项目
     */
    @Override
    public SysProject selectSysProjectByProjectId(Long projectId) {
        return sysProjectMapper.selectSysProjectByProjectId(projectId);
    }

    /**
     * 查询项目列表
     *
     * @param sysProject 项目
     * @return 项目
     */
    @Override
    public List<SysProject> selectSysProjectList(SysProject sysProject) {



        List<SysProject> sysProjectList = sysProjectMapper.selectNewSysProjectList(sysProject);

        for (SysProject project : sysProjectList) {
            if (project.getContractName() != null) {
                SysContract contract = sysContractMapper.selectSysContractByContractId(Long.valueOf(project.getContractName()));

                if (contract != null) {
                    project.setContractNick(contract.getContractName());
                }
            }
        }


        return sysProjectList;
    }

    /**
     * 新增项目
     *
     * @param sysProject 项目
     * @return 结果
     */
    @Override
    public int insertSysProject(SysProject sysProject) {
        sysProject.setUserId(SecurityUtils.getUserId());
        sysProject.setDeptId(SecurityUtils.getDeptId());
        sysProject.setCreateTime(DateUtils.getNowDate());
        return sysProjectMapper.insertSysProject(sysProject);
    }

    /**
     * 修改项目
     *
     * @param sysProject 项目
     * @return 结果
     */
    @Override
    public int updateSysProject(SysProject sysProject) {
        sysProject.setUpdateTime(DateUtils.getNowDate());
        return sysProjectMapper.updateSysProject(sysProject);
    }

    /**
     * 批量删除项目
     *
     * @param projectIds 需要删除的项目主键
     * @return 结果
     */
    @Override
    public int deleteSysProjectByProjectIds(Long[] projectIds) {
        return sysProjectMapper.deleteSysProjectByProjectIds(projectIds);
    }

    /**
     * 删除项目信息
     *
     * @param projectId 项目主键
     * @return 结果
     */
    @Override
    public int deleteSysProjectByProjectId(Long projectId) {
        return sysProjectMapper.deleteSysProjectByProjectId(projectId);
    }


    @Override
    public AjaxResult listSelects() {

        List<CodeVo> result = new ArrayList<>();

        SysProject sysProject = new SysProject();

        Long deptId = SecurityUtils.getDeptId();
        SysDept sysDept = sysDeptMapper.selectDeptById(deptId);
        if (sysDept != null) {
            sysProject.setDeptNameParam(sysDept.getDeptAttr());
        }


        List<SysProject> list = sysProjectMapper.selectSysProjectList(sysProject);

        result = list.stream().map(c -> {

            CodeVo codeVo = new CodeVo();
            codeVo.setLabel(c.getProjectName());
            codeVo.setValue(c.getProjectId());

            codeVo.setProjectDetailVo(c);

            return codeVo;
        }).collect(Collectors.toList());

        return AjaxResult.success(result);
    }


    @Override
    public AjaxResult choseLis(SysProject sysProject) {




        List<SysProject> sysProjectList = sysProjectMapper.selectNewSysProjectList(sysProject);

        for (SysProject project : sysProjectList) {
            if (project.getContractName() != null) {
                SysContract contract = sysContractMapper.selectSysContractByContractId(Long.valueOf(project.getContractName()));

                if (contract != null) {
                    project.setContractNick(contract.getContractName());
                }
            }
        }


        return AjaxResult.success(sysProjectList);
    }

    @Override
    public void importExcelData(MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            System.out.println("上传的文件为空");
            return;
        }

        // 检查文件类型
        String fileName = file.getOriginalFilename();
        if (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls")) {
            System.out.println("请上传Excel文件");
            return;
        }

        try (InputStream inputStream = file.getInputStream()) {
            // 根据文件后缀创建对应的Workbook
            Workbook workbook;
            if (fileName.endsWith(".xlsx")) {
                workbook = WorkbookFactory.create(inputStream);
            } else {
                // 对于旧版.xls文件
                workbook = WorkbookFactory.create(inputStream);
            }

            // 读取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);

            if (sheet == null) {
                System.out.println("工作表为空");
                return;
            }

            // 从第二行开始读取（行索引从0开始，所以第二行是index=1）
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);

                if (row == null) {
                    continue; // 跳过空行
                }


                try {
                    // 使用工具方法获取单元格值，避免类型错误
                    String batchName = getCellStringValue(row.getCell(0));
                    String projectName = getCellStringValue(row.getCell(1));
                    String projectDesc = getCellStringValue(row.getCell(2));
                    String planStartDateStr = getCellStringValue(row.getCell(3));
                    Date planEndDate = getCellDateValue(row.getCell(4));
                    String accumulateNum = getCellStringValue(row.getCell(5));
                    String totalProcessNum = getCellStringValue(row.getCell(6));
                    String constructUnit = getCellStringValue(row.getCell(7));
                    String superviseAgency = getCellStringValue(row.getCell(8));
                    String projectLeader = getCellStringValue(row.getCell(9));
                    String leaderContact = getCellStringValue(row.getCell(10));
                    String safetyDirector = getCellStringValue(row.getCell(11));
                    String safetyDirectorContact = getCellStringValue(row.getCell(12));
                    String residentSupervisor = getCellStringValue(row.getCell(13));
                    String residentSupervisorContact = getCellStringValue(row.getCell(14));
                    String nextWeekPlan = getCellStringValue(row.getCell(15));
                    String riskLevel = getCellStringValue(row.getCell(16));
                    String actualWorkTimeStr = getCellStringValue(row.getCell(17));
                    String completionStatus = getCellStringValue(row.getCell(18));
                    String notes = getCellStringValue(row.getCell(19));

                    SysProject sysProject = new SysProject();
                    sysProject.setBatchName(batchName);
                    sysProject.setProjectName(projectName);
                    sysProject.setProjectDesc(projectDesc);
                    sysProject.setPlanStartDate(StrUtil.isNotBlank(planStartDateStr)
                            ? cn.hutool.core.date.DateUtil.parse(planStartDateStr, "yyyy-MM-dd")
                            : null);
                    sysProject.setPlanEndDate(planEndDate);
                    sysProject.setAccumulateNum(accumulateNum);
                    sysProject.setTotalProcessNum(totalProcessNum);
                    sysProject.setConstructUnit(constructUnit);
                    sysProject.setSuperviseAgency(superviseAgency);
                    sysProject.setProjectLeader(projectLeader);
                    sysProject.setLeaderContact(leaderContact);
                    sysProject.setSafetyDirector(safetyDirector);
                    sysProject.setSafetyDirectorContact(safetyDirectorContact);
                    sysProject.setResidentSupervisor(residentSupervisor);
                    sysProject.setResidentSupervisorContact(residentSupervisorContact);
                    sysProject.setNextWeekPlan(nextWeekPlan);
                    sysProject.setRiskLevel(riskLevel);
                    sysProject.setActualWorkTime(StrUtil.isNotBlank(actualWorkTimeStr)
                            ? cn.hutool.core.date.DateUtil.parse(actualWorkTimeStr, "yyyy-MM-dd")
                            : null);
                    sysProject.setCompletionStatus(completionStatus);
                    sysProject.setNotes(notes);
                    sysProject.setUserId(SecurityUtils.getUserId());

                    sysProjectMapper.insertSysProject(sysProject);

                } catch (Exception e) {
                    // 根据需要决定是跳过还是中断
                    continue;
                }
            }

            // 关闭工作簿
            workbook.close();

        } catch (IOException e) {
            System.out.println("读取Excel文件出错: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("处理Excel时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 安全地获取单元格的字符串值
     */
    private String getCellStringValue(Cell cell) {
        if (cell == null) {
            return "";
        }

        // 处理公式单元格
        if (cell.getCellType() == CellType.FORMULA) {
            Workbook workbook = cell.getSheet().getWorkbook();
            FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            cell = evaluator.evaluateInCell(cell);
        }

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                // 处理日期类型
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cn.hutool.core.date.DateUtil.format(cell.getDateCellValue(), "yyyy-MM-dd");
                } else {
                    // 处理数字类型
                    double numericValue = cell.getNumericCellValue();
                    if (numericValue % 1 == 0) {
                        // 整数处理
                        return String.valueOf((long) numericValue);
                    } else {
                        // 小数处理
                        return String.valueOf(numericValue);
                    }
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            default:
                return "";
        }
    }

    /**
     * 获取单元格的日期值
     */
    private Date getCellDateValue(Cell cell) {
        if (cell == null) {
            return null;
        }

        // 处理公式单元格
        if (cell.getCellType() == CellType.FORMULA) {
            Workbook workbook = cell.getSheet().getWorkbook();
            FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            cell = evaluator.evaluateInCell(cell);
        }

        if (cell.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell)) {
            return cell.getDateCellValue();
        } else {
            // 如果不是日期类型，尝试从字符串解析
            String cellValue = getCellStringValue(cell);
            if (StrUtil.isNotBlank(cellValue)) {
                try {
                    return cn.hutool.core.date.DateUtil.parse(cellValue, "yyyy-MM-dd");
                } catch (Exception e) {
                    return null;
                }
            }
        }
        return null;
    }
}
